import { RbacPermissionType } from '@/data/auth/permission';
import { PageParams } from '@/data/result';
import { PermissionTypeEnum, PermissionTypeValueEnum } from '@/enums/auth';
import UpdateModal from '@/pages/auth/rbacPermission/components/UpdateModal';
import { tablePage } from '@/services/data';
import { handleAdd, handleRemove, handleRemoveList, handleUpdate } from '@/services/handle';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, Tag } from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacPermissionType>();
  const [selectedRowsState, setSelectedRows] = useState<RbacPermissionType[]>([]);

  const columns: ProColumns<RbacPermissionType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },

    {
      title: '权限标识',
      dataIndex: 'urlPerm',
    },
    {
      title: '权限类型',
      dataIndex: 'type',
      render: (text) => {
        const type = typeof text === 'string' || typeof text === 'number' ? text : '';
        return <Tag color="blue">{PermissionTypeValueEnum[type] || type}</Tag>;
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
            setShowDetail(false);
          }}
        >
          更新
        </a>,
        <a
          key="remove"
          onClick={async () => {
            await handleRemove('/system/rbacPermission', record.id);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
            setShowDetail(false);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<RbacPermissionType, PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => tablePage('/system/rbacPermission', params)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList('/system/rbacPermission', selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建"
        width="400px"
        open={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd('/system/rbacPermission', value as RbacPermissionType);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '权限类型为必填项',
            },
          ]}
          width="md"
          name="type"
          valueEnum={PermissionTypeValueEnum}
          label={'权限类型'}
          placeholder={'请选择权限类型'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '权限标识为必填项',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                const type = getFieldValue('type');
                // 根据不同类型定义不同的正则表达式
                let regExp;

                switch (type) {
                  case PermissionTypeEnum.Api:
                    // 格式: /auth/rbacUser/page (不含后缀)
                    regExp = /^\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+$/;
                    break;
                  case PermissionTypeEnum.Admin:
                    console.log('adminnnn');
                    // 格式: /auth/rbacUser/page.admin (含.admin后缀)
                    regExp = /^\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\.admin$/;
                    break;
                  case PermissionTypeEnum.Open:
                    // 格式: /auth/rbacUser/page.open (含.open后缀)
                    regExp = /^\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\.open$/;
                    break;
                  default:
                    return Promise.resolve();
                }

                if (regExp.test(value)) {
                  return Promise.resolve();
                }

                // 根据类型返回对应的错误提示
                const messages = {
                  '0': '权限标识格式应为 /xxx/xxx/xxx',
                  '1': '权限标识格式应为 /xxx/xxx/xxx.admin',
                  '2': '权限标识格式应为 /xxx/xxx/xxx.open',
                };

                return Promise.reject(new Error(messages[type] || '权限标识格式不正确'));
              },
            }),
          ]}
          width="md"
          name="urlPerm"
          label={'权限标识'}
          placeholder={'请输入权限标识'}
        />

        <ProFormText
          rules={[
            {
              required: true,
              message: '备注为必填项',
            },
          ]}
          width="md"
          name="remark"
          label={'备注'}
          placeholder={'请输入备注'}
        />
      </ModalForm>
      <UpdateModal
        onSubmit={async (value) => {
          const success = await handleUpdate('/system/rbacPermission', value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<RbacPermissionType>
            column={1}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<RbacPermissionType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
